import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_shipper/AppConfig/Config.dart';
import 'package:sph_shipper/Main/EditInformation/EditShipperAuth.dart';
import 'package:sph_shipper/Main/Information/InvoiceHeader.dart';

import '../../AppConfig/LocalStorage.dart';
import '../../AppConfig/RouteAct.dart';
import '../../AppConfig/ShowDialog.dart';
import '../../AppConfig/StringEncapsulation.dart';
import '../../http/api.dart';
import '../../l10n/messages.dart';
import '../CustomerService/ModifyPhoneNumber.dart';
import '../EditInformation/EditIDCard.dart';
import 'package:image/image.dart' as img;
class InformationView extends StatefulWidget {
  const InformationView({super.key, required this.dataMap});
  final Map dataMap;
  @override
  State<InformationView> createState() => _InformationViewState();
}

class _InformationViewState extends State<InformationView> {
  final ImagePicker picker = new ImagePicker();
  File? _userImage;
  Map userMap={};
  String headPath="";
  late PermissionStatus status;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    userMap=widget.dataMap;
    getUserMessage();
    getDicTree();
  }

  void getUserMessage() async {
    String? token= await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));

    dio.get<String>(MyServiceUrl.header+'api/auth/shipper/user/getLoginUser')
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(r.toString());

        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          setState(() {
            userMap=jsonMap['data'];
          });
        } else {}
        // 打印结果
        print('Code: $code');
      });
    }).catchError((error) {
      print(error);
    });
  }
  void getDicTree() async {
    String? token= await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));

    dio.get<String>(MyServiceUrl.header+'api/system/dev/dict/tree?category=BIZ&type=SHIPPER')
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(r.toString());

        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          setState(() {
            print(jsonMap['data'][1]['children'][1]['children'][1]['children']);
          });
        } else {}
        // 打印结果
        print('Code: $code');
      });
    }).catchError((error) {
      print(error);
    });
  }


  //获取图片路径
  Future<void> uploadSingleFile(String fileData) async {
    String? token = await TokenManager.getToken();
    String? shipperId =await UserIdManager.getUserID();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(
      MyServiceUrl.header +
          'api/system/dev/file/uploadSingleFile',
      data: {
        "type":"ShipperAvatar",
        "typeKey":shipperId,
        "fileData":fileData,
        "fileFormat":"jpg"
      },
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          headPath=jsonMap['data'].toString();
          upLoadHeadPic();
        } else {
          BrnToast.show(jsonMap['msg'], context);
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }

  Future<void> upLoadHeadPic() async {
    print("路径：${headPath}");
    String? userId= await UserIdManager.getUserID();
    ApiManager.postData(
      context,
      'api/auth/shipper/user/editAvatar',
      {
        "userId":userId,
        "avatarPath":headPath,
      },
          (responseData) {
        setState(() {
          BrnToast.show("提交成功", context);
        });
      },
    );
  }

  String imageToBase64(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    String base64String = base64Encode(Uint8List.fromList(imageBytes));

    return base64String;
  }


  void printImageMemorySize(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    print('Original Image Memory Size: ${imageBytes.length} bytes');
  }

  Future<void> compressImage(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    img.Image image = img.decodeImage(Uint8List.fromList(imageBytes))!;

    // Adjust the quality and size as needed
    img.Image compressedImage = img.copyResize(image, width: 1024);

    List<int> compressedBytes = img.encodeJpg(compressedImage, quality: 80);

    // Create a new File for the compressed image
    File compressedFile = File('${imageFile.path}_compressed.jpg');
    await compressedFile.writeAsBytes(compressedBytes);

    print('Compressed Image Size: ${compressedBytes.length} bytes');

    convertToBase64(compressedFile);
  }

  Future<void> convertToBase64(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    String base64String = base64Encode(imageBytes);
    uploadSingleFile(base64String);

  }
  @override
  Widget build(BuildContext context) {
    var messages = AppLocalizations.of(context)!;
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Color.fromRGBO(248, 248, 248, 1),
      appBar: AppBar(
        backgroundColor: Color.fromRGBO(231, 112, 27, 0.85),
        title: Text(messages["个人信息"],style: TextStyle(color: Colors.white,fontSize: 16.sp,fontWeight: FontWeight.w300),),
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body:  userMap.isEmpty?Container(color: Colors.white,):
    Container(
    decoration: BoxDecoration(
    gradient: LinearGradient(
    colors: [MyColors.themeColor,MyColors.backgreyColor, MyColors.backgreyColor,MyColors.backgreyColor], // 渐变颜色数组
    begin: Alignment.topCenter, // 渐变开始的位置
    end: Alignment.bottomCenter, // 渐变结束的位置
    ),

    ),
    child:
      ListView(
        children: [
          Container(
            height: 159.7.h,
            width: screenSize.width ,
            // decoration: BoxDecoration(
            //   gradient: LinearGradient(
            //     colors: [MyColors.themeColor, Colors.white], // 渐变颜色数组
            //     begin: Alignment.topCenter, // 渐变开始的位置
            //     end: Alignment.bottomCenter, // 渐变结束的位置
            //   ),
            //
            // ),
            child: Column(
              // mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                GestureDetector(
                  child:
                  Container(
                    width: 60.w,
                    height: 60.h,
                    child: _userImage!=null?
                    ClipOval(
                      child: Image.file(_userImage!, width: 60.w,
                        height: 60.h, fit: BoxFit.cover,),
                    ):
                    userMap['avatarPath']!=null&&userMap['avatarPath']!=""?
                    CircleAvatar(
                      radius: 15,
                      backgroundImage: NetworkImage(MyServiceUrl.imgHeader +userMap['avatarPath']),
                    )
                        :  CircleAvatar(
                      radius: 15,
                      backgroundImage: AssetImage("lib/Images/login/默认头像.jpeg"),
                    ),
                  ),
                  onTap: (){
                    showModalBottomSheet(context: context, builder: (BuildContext context)
                    {
                      return Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(10)),
                          color: Colors.white,
                        ),
                        child:
                        Stack(

                          children: [

                            Column(
                              mainAxisSize: MainAxisSize.min,
                              mainAxisAlignment:MainAxisAlignment.center,

                              children:[

                                SizedBox(height: 8.h,),
                                Row(
                                  mainAxisAlignment:MainAxisAlignment.spaceBetween,
                                  children: [
                                    SizedBox(width: 20.w,),
                                    Text(messages["上传照片"],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 18.sp),),
                                    IconButton(onPressed: (){
                                      Navigator.of(context).pop();
                                    }, icon:Icon(Icons.close,color: MyColors.textColor,size: 30,)),
                                  ],
                                ),


                                SizedBox(height: 10.h,),
                                Row(
                                  children: [
                                    SizedBox(width: 38.w,),
                                    GestureDetector(
                                      child:   Column(
                                        children: [
                                          Image.asset("lib/Images/Authentication/相册icon.png",width:35.w ,height: 35.h,),
                                          Text(messages["相册"],style: TextStyle(color: Colors.black),),

                                        ],

                                      ),
                                      onTap: ()async{

                                        var status = await Permission.photos.request();
                                        if(status==PermissionStatus.denied){
                                          showPhotosFirstDialog(context);
                                        }else if(status==PermissionStatus.permanentlyDenied){
                                          showPhotosDialog(context);
                                        }else{
                                          Navigator.of(context).pop();
                                          final pickedFile = await picker.pickImage(source: ImageSource.gallery);

                                          if (pickedFile != null) {

                                            setState(() {
                                              _userImage = File(pickedFile.path);
                                              printImageMemorySize(_userImage!);
                                              print(_userImage);
                                              compressImage(_userImage!);
                                            });
                                          }
                                        }
                                      },
                                    ),

                                    SizedBox(width: 38.w,),
                                    GestureDetector(
                                      child: Column(
                                        children: [
                                          Image.asset("lib/Images/Authentication/拍照icon.png",width:35.w ,height: 35.h,),
                                          Text(messages["拍照"],style: TextStyle(color: Colors.black),),

                                        ],

                                      ),
                                      onTap: ()async{
                                        var status = await Permission.camera.request();
                                        if(status==PermissionStatus.denied){
                                          showCameraFirstDialog(context);
                                        }else if(status==PermissionStatus.permanentlyDenied){
                                          showCameraDialog(context);
                                        }else{
                                          Navigator.of(context).pop();
                                          final pickedFile = await picker.pickImage(source: ImageSource.camera);
                                          if (pickedFile != null) {
                                            setState(() {
                                              _userImage = File(pickedFile.path);
                                              printImageMemorySize(_userImage!);
                                              print(_userImage);
                                              compressImage(_userImage!);
                                            });
                                          }

                                        }

                                      },
                                    ),

                                  ],
                                ),
                                SizedBox(height: 40.h,),
                              ],

                            ),

                          ],

                        ),
                      );
                    }
                    );
                  },
                ),
                SizedBox(height: 8.h,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    userMap['personalInfo']!=null?
                    Text(userMap['realName'],style: TextStyle(color: Colors.white,fontSize:16.sp ),)
                    :Text("货主",style: TextStyle(color: Colors.white,fontSize:16.sp ),),
                    SizedBox(width: 8.w,),
                    userMap['authStatus']==0?
                    Image.asset("lib/Images/PersonCenter/未认证白色.png",width: 44.w,height: 18.h,)
                    :Image.asset("lib/Images/PersonCenter/已认证icon.png",width: 44.w,height: 18.h,),
                  ],
                ),
                SizedBox(height: 8.h,),
                Container(
                  margin: EdgeInsets.only(left: 10.w,right: 10.w),
                  height: 40.h,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10)),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [

                      Text("    "+messages["注册手机号"],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                      Row(
                        children: [
                          Text(maskPhoneNumber(userMap['phoneNum']),style: TextStyle(color: Colors.black,fontSize: 14.sp,),textAlign: TextAlign.center,),
                          TextButton(onPressed: (){
                            Navigator.push( context, FadeRoute(page:ModifyPhoneNumber(phoneNum: userMap['phoneNum'], userMap: userMap,)));
                          },
                              child: Text(messages["修改"],style: TextStyle(color: Color.fromRGBO(231, 112, 27, 0.85),fontWeight: FontWeight.w600,fontSize: 14.sp),)),
                        ],
                      ),

                    ],
                  ),
                ),
                SizedBox(height: 8.h,),


              ],
            ),
          ),
          // SizedBox(height: 8.h,),
          GestureDetector(
            child:  Container(
              margin: EdgeInsets.only(left: 10.w,right: 10.w),
              padding: EdgeInsets.only(right:12.w ),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(10)),
              ),
              child: Column(
                children: [
                  SizedBox(height: 12.h,),
                  userMap['personalInfo']!=null?
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Text("    "+messages["身份证信息"],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                          SizedBox(width: 4.w,),
                          if(compareDateWithCurrent(userMap['personalInfo']['validTo'])=="2"||compareDateWithCurrent(userMap['personalInfo']['validTo'])=="3")
                            BrnTagCustom.buildBorderTag(
                              tagText: '即将过期',
                              textColor: Colors.red,
                              borderColor: Colors.red,
                              borderWidth: 1,
                              fontSize: 9.sp,
                              textPadding: EdgeInsets.all(1),
                            ),
                          if(compareDateWithCurrent(userMap['personalInfo']['validTo'])=="4")
                            BrnTagCustom.buildBorderTag(
                              tagText: '已过期',
                              textColor: Colors.red,
                              borderColor: Colors.red,
                              borderWidth: 1,
                              fontSize: 9.sp,
                              textPadding: EdgeInsets.all(1),
                            ),
                          if(userMap['personalStatus']== 1)
                            BrnTagCustom.buildBorderTag(
                              tagText: '审核中',
                              textColor: Colors.red,
                              borderColor: Colors.red,
                              borderWidth: 1,
                              fontSize: 9.sp,
                              textPadding: EdgeInsets.all(1),
                            ),
                          if(userMap['personalStatus']== 2)
                            BrnTagCustom.buildBorderTag(
                              tagText: '已认证',
                              textColor: Colors.green,
                              borderColor: Colors.green,
                              borderWidth: 1,
                              fontSize: 9.sp,
                              textPadding: EdgeInsets.all(1),
                            ),
                        ],
                      ),
                      GestureDetector(
                        child: Text("编辑",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                        onTap: () async {
                          final result=await     Navigator.push( context, FadeRoute(page:EditIDCard(dataMap: userMap,)));
                          if(result!=null){
                            getUserMessage();
                          }
                        },
                      )
                    ],
                  )
                      :Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text("    "+messages["身份证信息"],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),

                    ],
                  ),

                  SizedBox(height: 12.h,),
                  Divider(color: Color.fromRGBO(240, 240, 240, 1),),
                  SizedBox(height: 12.h,),
                  userMap['personalInfo']!=null?
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text("    "+maskIdNumber(userMap['personalInfo']['idNum']),style: TextStyle(color: Colors.black,fontSize: 14.sp,),),
                    ],
                  )
                      :GestureDetector(
                    child: Container(
                      width: 200.w,
                      height: 40.h,
                      decoration: BoxDecoration(
                        color: MyColors.themeColor,
                        borderRadius: BorderRadius.all(Radius.circular(60)),
                      ),
                      child:Center(
                        child:Text("+"+messages["前往实名认证"],style: TextStyle(color: Colors.white,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                      ),

                    ),
                    onTap: ()async{
                      final result=await  Navigator.push( context, FadeRoute(page:EditIDCard(dataMap: userMap,)));
                      if(result!=null){
                        getUserMessage();
                      }
                    },
                  ),
                  SizedBox(height: 12.h,),
                ],
              ),
            ),
            onTap: ()async{
              final result=await     Navigator.push( context, FadeRoute(page:EditIDCard(dataMap: userMap,)));
              if(result!=null){
                getUserMessage();
              }
            },
          ),

          SizedBox(height: 8.h,),
          GestureDetector(
            child:  Container(
              margin: EdgeInsets.only(left: 10.w,right: 10.w),
              padding: EdgeInsets.only(right: 12.w),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(10)),
              ),
              child: Column(
                children: [
                  SizedBox(height: 12.h,),
                  userMap['companyInfo']!=null?
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text("    "+messages["企业信息"],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                      GestureDetector(
                        child: Text("编辑",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                        onTap: () async {
                          final result=await  Navigator.push( context, FadeRoute(page:EditShipperAuth(dataMap: userMap,)));
                          if(result!=null){
                            getUserMessage();
                          }
                        },
                      )
                    ],
                  )
                      :Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text("    "+messages["企业信息"],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                    ],
                  ),
                  SizedBox(height: 12.h,),
                  Divider(color: Color.fromRGBO(240, 240, 240, 1),),
                  SizedBox(height: 12.h,),
                  userMap['companyInfo']!=null?
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text("    "+userMap['companyInfo']['name'],style: TextStyle(color: Colors.black,fontSize: 14.sp,),),
                    ],
                  )
                      :GestureDetector(
                    child: Container(
                      width: 200.w,
                      height: 40.h,
                      decoration: BoxDecoration(
                        color: Color.fromRGBO(231, 112, 27, 0.85),
                        borderRadius: BorderRadius.all(Radius.circular(60)),
                      ),
                      child:Center(
                        child:Text("+"+messages["前往企业认证"],style: TextStyle(color: Colors.white,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                      ),
                    ),
                    onTap: ()async{
                      if(userMap['authStatus']!=2){
                        BrnToast.show("请先完成实名认证", context);
                      }else{
                        final result=await    Navigator.push( context, FadeRoute(page:EditShipperAuth(dataMap: userMap,)));
                        if(result!=null){
                          getUserMessage();
                        }
                      }


                    },
                  ),
                  SizedBox(height: 12.h,),
                ],
              ),
            ),
            onTap: ()async{
              if(userMap['authStatus']!=2){
                BrnToast.show("请先完成实名认证", context);
              }else{
                final result=await    Navigator.push( context, FadeRoute(page:EditShipperAuth(dataMap: userMap,)));
                if(result!=null){
                  getUserMessage();
                }
              }
            },
          )



        ],

      ),
    ),
    );
  }
}
